import type { LngLatLike } from 'mapbox-gl';
import type { Station, StationManagerEvents } from '../../Mapless/index.d';
import { withMapboxMarker } from '../../WithMap';
import StationsClickPanel from './StationsClickPanel';

const StationClickPanelMarker = withMapboxMarker(StationsClickPanel);
export default StationClickPanelMarker;

const onDefaultEvent = (
  e: StationManagerEvents['stationsSelected'][0],
  stations: Station[] | undefined | null,
) => {
  const ss = stations?.filter((item) =>
    e.stations?.some((s) => s.id === item.id),
  );
  if (!ss) {
    return null;
  }
  const sum = ss.reduce(
    (acc, { longitude, latitude }) => {
      acc.lng += Number(longitude);
      acc.lat += Number(latitude);
      return acc;
    },
    { lng: 0, lat: 0 },
  );
  const center = [sum.lng / ss.length, sum.lat / ss.length] as LngLatLike;
  return {
    props: {
      stations: ss,
    },
    lngLat: center,
  };
};

export { onDefaultEvent };
